<template>
  <view
    class="pronunciation"
    :class="{ between: showWordInfo, end: !showWordInfo }"
  >
    <view class="info" v-if="showWordInfo && !isShowResult">
      <view class="word">
        <text
          v-for="(item, index) in wordData.segList"
          :key="index"
          :class="{
            active: item.zd,
          }"
        >
          {{ item.fc }}
        </text>
      </view>
      <view class="phonetic">
        【/
        <text v-for="(item, index) in wordData.segList" :key="index">
          {{ item.ipaUs }}
        </text>
        /】
        <image
          @click="play()"
          src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/yinliang.png"
          mode="scaleToFill"
        />
      </view>
      <view class="interpretation">
        {{ wordData.wordParaphrase }}
      </view>
    </view>
    <template v-if="showResultType === '1'">
      <view class="result1" v-if="isShowResult">
        <view class="result1_title"> AI发音测评 </view>
        <view class="result1_score">
          <view class="score1">
            <view class="score1_num">
              <image src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/word/star.png" mode="scaleToFill" />
              <view>{{ score }}分</view>
              <image src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/word/star.png" mode="scaleToFill" />
            </view>
            <view class="score1_tips">
              <template v-if="isPass"> 不错喔，继续加油吧 </template>
              <template v-else-if="!isPass && recorderCount < passCount">
                总共{{ passCount }}次机会，你还有{{
                  passCount - recorderCount
                }}次机会，加油哦
              </template>
              <template v-else-if="!isPass && recorderCount === passCount">
                没关系的，测试下一个单词吧
              </template>
            </view>
          </view>
        </view>
        <view class="result1_content">
          <view class="phoneme1">
            <view class="phoneme1_title">
              <text>标准发音</text>
              <text>音素匹配</text>
            </view>
            <view class="phoneme1_container">
              <view
                class="phoneme1_content"
                v-for="(item, index) in syllArray"
                :key="index"
              >
                <text>{{ item.content }}</text>
                <text
                  class="error"
                  :class="{
                    correct: item.score >= passScore,
                  }"
                  >{{ item.score }}</text
                >
              </view>
            </view>
          </view>
        </view>
      </view>
    </template>
    <template v-if="showResultType === '2'">
      <u-popup
        class="custom-popup"
        v-model="isShowResult"
        :zoom="false"
        mode="bottom"
        width="100%"
        height="880rpx"
        :mask-custom-style="{
          background: 'rgba(0, 0, 0, 0.5)',
        }"
        @close="handleClosePopup"
      >
        <view class="result2">
          <view class="result2_content">
            <view class="result2_title"> AI发音测评 </view>
            <view class="result2_box">
              <view class="result2_img">
                <image
                  src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/robot.gif"
                  mode="scaleToFill"
                />
              </view>
              <view class="result2_section">
                <view class="score2">
                  <view class="score2_num">
                    <image
                      src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/word/star.png"
                      mode="scaleToFill"
                    />
                    <view>{{ score }}分</view>
                    <image
                      src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/word/star.png"
                      mode="scaleToFill"
                    />
                  </view>
                  <view class="score2_tips">
                    <template v-if="isPass"> 不错喔，继续加油吧 </template>
                    <template v-else-if="!isPass && recorderCount < passCount">
                      总共{{ passCount }}次机会，你还有{{
                        passCount - recorderCount
                      }}次机会，加油哦
                    </template>
                    <template
                      v-else-if="!isPass && recorderCount === passCount"
                    >
                      没关系的，测试下一个单词吧
                    </template>
                  </view>
                </view>
                <view class="phoneme2">
                  <view class="phoneme2_title">
                    <text>标准发音</text>
                    <text>音素匹配</text>
                  </view>
                  <view class="phoneme2_container">
                    <view
                      class="phoneme2_content"
                      v-for="(item, index) in syllArray"
                      :key="index"
                    >
                      <text>{{ item.content }}</text>
                      <text
                        class="error"
                        :class="{
                          correct: item.score >= passScore,
                        }"
                        >{{ item.score }}</text
                      >
                    </view>
                  </view>
                </view>
                <view class="result2_btn">
                  <view class="result2_btn_content" @click="play()">
                    <text>播放原声</text>
                  </view>
                  <view class="result2_btn_content" @click="playVoice()">
                    <text>播放录音</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </u-popup>
    </template>
    <view class="record">
      <view class="record_content" v-if="!isRecord">
        <view class="record_btn">
          <view class="record_btn_content">
            <view
              class="record_btn_box"
              @longpress="record()"
              @touchend="endRecord()"
            >
              <image src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/bofang.png" mode="widthFix" />
            </view>
            <view class="record_btn_text"> 长按录音 </view>
          </view>
        </view>
      </view>
      <view class="record_content" v-else>
        <view class="record_btn">
          <view class="record_btn_content">
            <view class="record_btn_box" @click="playVoice()">
              <image src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/sound.png" mode="widthFix" />
            </view>
            <view class="record_btn_text"> 我的录音 </view>
          </view>
          <view
            v-if="!isPass && recorderCount < passCount"
            class="record_btn_content"
            @click="practiceAgain()"
          >
            <view class="record_btn_box">
              <image src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/again.png" mode="widthFix" />
            </view>
            <view class="record_btn_text"> 再次练习 </view>
          </view>
          <view
            v-if="isPass || recorderCount === passCount"
            class="record_btn_content"
            @click="next()"
          >
            <view class="record_btn_box">
              <image src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/next.png" mode="scaleToFill" />
            </view>
            <view class="record_btn_text"> 下一题 </view>
          </view>
        </view>
      </view>
    </view>
    <Tips :show="showTips" :content="tipsContent"></Tips>
    <u-popup
      class="custom-popup"
      v-model="recordShow"
      :zoom="false"
      mode="center"
      width="434rpx"
      height="316rpx"
      :mask-close-able="false"
      :mask-custom-style="{
        background: 'rgba(0, 0, 0, 0.5)',
      }"
    >
      <view class="record-popup">
        <view class="record-popup_top">
          <image src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/sound.png" mode="scaleToFill" />
          <view class="record-popup_shape">
            <view></view>
            <view></view>
            <view></view>
            <view></view>
            <view></view>
            <view></view>
          </view>
        </view>
        <view class="record-popup_bottom"> 手指松开 进行发送 </view>
      </view>
    </u-popup>
  </view>
</template>
<script>
import permision from "@/js_sdk/wa-permission/permission.js";
import parser from "fast-xml-parser";
import dictList from "@/libs/PronunciationDict";

const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;

const englishAudioContext = uni.createInnerAudioContext();
englishAudioContext.autoplay = true;
export default {
  name: "Pronunciation-Test",
  props: {
    wordData: {
      type: Object,
      default: null,
    },
    showWordInfo: {
      type: Boolean,
      default: true,
    },
    showResultType: {
      type: String,
      default: "1",
    },
    passCount: {
      type: Number,
      default: 3,
    },
  },
  created() {
    // #ifdef APP-PLUS
    this.isIos = plus.os.name == "iOS";
    // #endif
    let self = this;
    recorderManager.onStop(function (res) {
      self.voicePath = res.tempFilePath;
      self.uploadVoice();
    });
  },
  data() {
    return {
      // 语音配置
      isIos: true,
      voicePath: "",
      recordOptions: {
        duration: 60000,
        sampleRate: 16000,
        encodeBitRate: 48000,
      },
      permisionIosMap: {
        location: "位置",
        camera: "摄像头",
        photoLibrary: "相册",
        record: "麦克风",
        push: "推送",
        contact: "通讯录",
        calendar: "日历",
        memo: "备忘录",
      },
      permisionAndroidMap: {
        "android.permission.ACCESS_FINE_LOCATION": "位置",
        "android.permission.ACCESS_COARSE_LOCATION": "模糊位置",
        "android.permission.CAMERA": "摄像头",
        "android.permission.READ_EXTERNAL_STORAGE": "外部存储(含相册)读取",
        "android.permission.WRITE_EXTERNAL_STORAGE": "外部存储(含相册)写入",
        "android.permission.RECORD_AUDIO": "麦克风",
        "android.permission.READ_CONTACTS": "通讯录读取",
        "android.permission.WRITE_CONTACTS": "通讯录写入",
        "android.permission.READ_CALENDAR": "日历读取",
        "android.permission.WRITE_CALENDAR": "日历写入",
        "android.permission.READ_SMS": "短信读取",
        "android.permission.SEND_SMS": "短信发送",
        "android.permission.RECEIVE_SMS": "接收新短信",
        "android.permission.READ_PHONE_STATE": "获取手机识别码等信息的",
        "android.permission.CALL_PHONE": "拨打电话",
        "android.permission.READ_CALL_LOG": "获取通话记录",
      },
      // 熟练读音
      recordShow: false,
      isRecord: false,
      isRejected: "false",
      score: 0,
      passScore: 90,
      isPass: false,
      isShowResult: false,
      isCanClick: true,
      timerId: null,
      second: 0,
      minute: 0,
      secondNumber: "",
      minuteNumber: "",
      recorderCount: 0,
      syllArray: [],
      showTips: false,
      tipsContent: "请不要乱读哦~",
    };
  },
  methods: {
    initData() {
      this.isShowResult = false;
      this.isRecord = false;
    },
    play() {
      if (!englishAudioContext.paused) return;
      englishAudioContext.src = this.wordData.wordAudio;
      englishAudioContext.play();
    },
    record() {
      if (!this.isCanClick) return;
      this.isCanClick = false;
      setTimeout(() => {
        this.isCanClick = true;
      }, 1000);
      if (this.isIos) {
        this.judgeIosPermission("record");
      } else {
        this.requestAndroidPermission("android.permission.RECORD_AUDIO");
      }
    },
    judgeIosPermission: function (permisionID) {
      var result = permision.judgeIosPermission(permisionID);
      var strStatus = result ? "已" : "未";
      if (!result) {
        uni.showModal({
          title: "",
          content:
            this.permisionIosMap[permisionID] +
            "权限" +
            strStatus +
            "获得授权,是否去开启？",
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              plus.runtime.openURL("app-settings://");
            }
          },
        });
      } else {
        this.startRecord();
      }
    },
    async requestAndroidPermission(permisionID) {
      var result = await permision.requestAndroidPermission(permisionID);
      var strStatus;
      if (result == 1) {
        strStatus = "已获得授权";
        this.startRecord();
      } else if (result == 0) {
        strStatus = "未获得授权";
      } else {
        strStatus = "被永久拒绝权限";
        uni.showModal({
          title: "",
          content: this.permisionAndroidMap[permisionID] + "权限" + strStatus,
          showCancel: false,
        });
      }
    },
    startRecord() {
      recorderManager.start(this.recordOptions);
      this.time();
      this.recordShow = true;
    },
    endRecord() {
      recorderManager.stop();
    },
    handleEndRecordData() {
      this.recordShow = false;
      clearInterval(this.timerId);
      this.second = 0;
      this.minute = 0;
    },
    playVoice() {
      if (!englishAudioContext.paused) return;
      if (this.voicePath) {
        innerAudioContext.src = this.voicePath;
        innerAudioContext.play();
      }
    },
    uploadVoice() {
      this.handleEndRecordData();
      this.$upload(this.voicePath, { wordText: this.wordData.word })
        .then((res) => {
          let xml = res.data;
          let grade = parser.parse(xml, {
            attributeNamePrefix: "",
            ignoreAttributes: false,
          });
          if (grade) {
            let read_chapter =
              grade.xml_result.read_sentence.rec_paper.read_chapter;
            this.getSyllData(read_chapter);
            this.isRejected = read_chapter.is_rejected;
            if (this.isRejected === "true") {
              this.showTips = true;
              this.tipsContent = "请不要乱读哦~";
              setTimeout(() => {
                this.showTips = false;
              }, 2000);
            }
            this.recorderCount++;
            this.score = Number(read_chapter.total_score).toFixed(2);
            this.isPass = this.score >= this.passScore ? true : false;
            this.$playBgAudio(this.isPass ? "correct" : "error");
            this.saveRecord();
            this.isRecord = true;
            this.isShowResult = true;
          }
        })
        .catch((err) => {
          this.showTips = true;
          this.tipsContent = "识别失败~";
          setTimeout(() => {
            this.showTips = false;
          }, 2000);
          this.score = Number(0).toFixed(2);
          this.isPass = this.score >= this.passScore ? true : false;
          this.saveRecord();
          this.isRecord = true;
          this.isShowResult = true;
        });
    },
    practiceAgain() {
      this.initData();
    },
    time() {
      this.timerId = setInterval(() => {
        this.second++;
        if (this.second > 59) {
          this.second = 0;
          this.minute++;
        }
        if (this.second < 10) {
          this.secondNumber = this.second.toString().padStart(2, "0");
        } else {
          this.secondNumber = this.second.toString();
        }
        if (this.minute < 10) {
          this.minuteNumber = this.minute.toString().padStart(2, "0");
        } else {
          this.minuteNumber = this.minute.toString();
        }
      }, 1000);
    },
    getSyllData(result) {
      let syllArray = [];
      let sentence = result.sentence;
      let anArray = [];
      if (!Array.isArray(sentence)) {
        anArray.push(sentence);
      } else {
        anArray = sentence;
      }
      anArray.forEach((item) => {
        let anWordArray = [];
        if (!Array.isArray(item.word)) {
          anWordArray.push(item.word);
        } else {
          anWordArray = item.word;
        }
        anWordArray.forEach((item) => {
          if (item.content === "fil" || item.content === "sil") return;
          let anSyllArray = [];
          if (!Array.isArray(item.syll)) {
            anSyllArray.push(item.syll);
          } else {
            anSyllArray = item.syll;
          }
          anSyllArray.forEach((item) => {
            let syll_score = Number(item.syll_score).toFixed(2);
            const nonStandard = item.content;
            const splitResult = nonStandard.split(" ");
            const standardResult = splitResult
              .map((phoneme) => {
                const found = dictList.find(
                  (item) => item.nonstandard === phoneme
                );
                return found ? found.standard : phoneme; // 如果找到映射则替换，否则保持原样
              })
              .join(" ");
            let syll_content = standardResult;
            syllArray.push({
              content: syll_content,
              score: syll_score,
            });
          });
        });
      });
      this.syllArray = syllArray;
    },
    handleClosePopup() {
      this.$emit("complete", this.isPass, this.recorderCount, this.passCount);
      this.initData();
    },
    next() {
      this.$emit("next", this.isPass ? true : false);
      this.recorderCount = 0;
      this.initData();
    },
    saveRecord() {
      console.log("上传记录");
      this.$emit("save", this.score, this.isPass);
    },
  },
};
</script>
<style scoped lang="scss">
@import "./PronunciationTest";
</style>
  